# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
# Project developers.  See the top-level LICENSE file for dates and other
# details.  No copyright assignment is required to contribute to VisIt.

#*****************************************************************************
# Modifications:
#    Kathleen Biagas, Thu Nov  8 10:05:40 PST 2018
#    Added VISIT_MESAGL_DIR, VISIT_LLVM_DIR, guard some of the string
#    replacements with tests for whether the VISIT_XXX_DIR var exists.
#
#    Kathleen Biagas, Mon Feb 25 15:53:24 PST 2019
#    Skip icet, rename OSMesa to GL.
#
#    Kathleen Biagas, Thu Jul 18 10:39:23 PDT 2019
#    Add special handling for tbb, ospray, embree. Move some code to
#    non-windows. Remove slivr libraries from the suppression list as they
#    are no longer part of VisIt.
#
#    Kevin Griffin, Thu Aug 8 18:20:01 PDT 2019
#    Fixed the Qt and qwt frameworks path for OSX and the syntax error produced from
#    filtering the right parenthesis in certain cases.
#
#    Kathleen Biagas, Fri March 10, 2023
#    Filter out vtkm_* libraries as they are static.
#
#    Kathleen Biagas, Wed Nov  8 10:03:29 PST 2023
#    Handle VTK9 and QT 6 named targets. For Qt, use QT_MAJOR_VERSION instead
#    of '5' or '6', and add uitools (needed for qt 6).
#
#    Kathleen Biagas, Thu May 2, 2024
#    Parse "VTK::vtk" token differently (e.g. "VTK::vtksys" should not
#    become "vtkvtksys").
#
#****************************************************************************/
cmake_policy(SET CMP0011 NEW)
cmake_policy(SET CMP0057 NEW)

set(VISIT_BINARY_DIR  @VISIT_BINARY_DIR@)
set(VISIT_PYTHON_DIR  @VISIT_PYTHON_DIR@)
set(VISIT_ZLIB_DIR    @VISIT_ZLIB_DIR@)
set(VISIT_BOOST_DIR   @VISIT_BOOST_DIR@)
set(VISIT_OPENEXR_DIR @VISIT_OPENEXR_DIR@)
set(VISIT_QWT_DIR     @VISIT_QWT_DIR@)
set(VTK_TARGETS       @VTK_VALID_TARGETS@)
set(VTK_SMALL_VERSION @VTK_MAJOR_VERSION@.@VTK_MINOR_VERSION@)
set(PYTHON_SMALL_VERSION @PYTHON_MAJOR_VERSION@@PYTHON_MINOR_VERSION@)
set(VISIT_MESAGL_DIR  @VISIT_MESAGL_DIR@)
set(VISIT_LLVM_DIR    @VISIT_LLVM_DIR@)
set(QT_MAJOR_VERSION  @QT_MAJOR_VERSION@)

function(FILTER_VISIT_LIB_DEPENDENCIES filename)
    file(STRINGS ${filename}.in lines)
    file(WRITE   ${filename} "# Filtered version\n")

    foreach(line ${lines})
        if("${line}" MATCHES "CMAKE_MAJOR")
            continue()
        elseif("${line}" MATCHES "CMake 2.6")
            continue()
        elseif("${line}" MATCHES "else")
            # code below the else is for very early versions of cmake, which we are
            # already guaranteed to not be using, so stop processing the file
            break()
        endif()

        set(outputLine TRUE)
        if("${line}" MATCHES ".*Plot[_ser|_par]*_LIB_DEPENDS.*")
            set(outputLine FALSE)
        elseif("${line}" MATCHES ".*Operator[_ser|_par]*_LIB_DEPENDS.*")
            set(outputLine FALSE)
        elseif("${line}" MATCHES ".*Database[_ser|_par]*_LIB_DEPENDS.*")
            set(outputLine FALSE)
        endif()
        if (NOT outputLine)
            continue()
        endif()
        # are there others that should be suppressed?
        foreach(suppress visit_writer visitfrontend visitmodule proxyexample)
            if("${line}" MATCHES ".*${suppress}_LIB_DEPENDS.*")
                set(outputLine FALSE)
            endif()
        endforeach()
        if (NOT outputLine)
            continue()
        endif()

        if(NOT WIN32)
            if(VISIT_PYTHON_DIR AND "${line}" MATCHES "python")
                string(REPLACE "${VISIT_PYTHON_DIR}/lib/"
                               ""
                               line "${line}")
            endif()
            if(VISIT_ZLIB_DIR AND "${line}" MATCHES "zlib")
                string(REPLACE "${VISIT_ZLIB_DIR}/lib/"
                               ""
                               line "${line}")
            endif()
            if(VISIT_BOOST_DIR AND "${line}" MATCHES "boost")
                string(REPLACE "${VISIT_BOOST_DIR}/lib"
                               ""
                               line "${line}")
            endif()
            if(VISIT_QWT_DIR AND "${line}" MATCHES "qwt")
                if(APPLE)
                    string(REPLACE "${VISIT_QWT_DIR}/lib/"
                                   "\${VISIT_LIBRARY_DIR}/"
                                   line "${line}")
                else()
                    string(REPLACE "${VISIT_QWT_DIR}/lib/"
                                   ""
                                   line "${line}")
                endif()
            endif()
        endif()
        if(VISIT_OPENEXR_DIR)
            if(APPLE) # built as dynamic on apple and window
                string(REPLACE "${VISIT_OPENEXR_DIR}/lib"
                               "\${VISIT_LIBRARY_DIR}"
                                line "${line}")
            elseif(UNIX) # built as static on linux
                string(REPLACE "${VISIT_OPENEXR_DIR}/lib"
                               "\${VISIT_ARCHIVE_DIR}"
                                line "${line}")
            endif()
        endif()
        if(VISIT_MESAGL_DIR)
            string(REPLACE "${VISIT_MESAGL_DIR}/lib"
                           "\${VISIT_LIBRARY_DIR}/mesagl"
                            line "${line}")
        endif()
        if(VISIT_LLVM_DIR)
            string(REPLACE "${VISIT_LLVM_DIR}/lib"
                           "\${VISIT_LIBRARY_DIR}/mesagl"
                            line "${line}")
        endif()

        # When we get here, we need to output a filtered line.
        # The line is tokenized to make filtering easier (albeit slower).
        #   * Replace vtk<lib> with vtk<lib>-<vtk_small_version>
        #   * Replace Qt${QT_MAJOR_VERSION}::<lib> with Qt${QT_MAJOR_VERSION}<lib>
        #   * Remove vtkm_*
        #   * Remove quotes surrounding 'xxx_LIB_DEPENDS'
        set(skip_next_token FALSE)
        foreach(token ${line})
            if(skip_next_token)
                set(skip_next_token FALSE)
                continue()
            endif()
            if(${token} MATCHES "_LIB_DEPENDS")
                set(newtoken ${token})
                if(WIN32)
                    if(${token} MATCHES "viewer_LIB_DEPENDS")
                        # change viewer to viewerlib
                        string(REPLACE "viewer_LIB_DEPENDS"
                                       "viewerlib_LIB_DEPENDS" newtoken ${token})
                    elseif(${token} MATCHES "gui_LIB_DEPENDS")
                        # change gui to guilib
                        string(REPLACE "gui_LIB_DEPENDS"
                                       "guilib_LIB_DEPENDS" newtoken ${token})
                    endif()
                endif()
                # remove surrounding quotes
                string(REPLACE "\"" "@@@@@" replace_quote ${newtoken})
                string(REGEX REPLACE "@@@@@([a-zA-Z_]+)_LIB_DEPENDS@@@@@"
                       "\\1_LIB_DEPENDS"
                       rem_quote ${replace_quote})
                string(REPLACE "@@@@@" "\"" newtoken ${rem_quote})
            elseif(token MATCHES "Qt${QT_MAJOR_VERSION}::")
                if(APPLE)
                    if(token MATCHES "Qt${QT_MAJOR_VERSION}::Concurrent|Qt${QT_MAJOR_VERSION}::Core|Qt${QT_MAJOR_VERSION}::Gui|Qt${QT_MAJOR_VERSION}::Network|Qt${QT_MAJOR_VERSION}::OpenGL|Qt${QT_MAJOR_VERSION}::PrintSupport|Qt${QT_MAJOR_VERSION}::Qml|Qt${QT_MAJOR_VERSION}::Svg|Qt${QT_MAJOR_VERSION}::Widgets|Qt${QT_MAJOR_VERSION}::Xml|Qt${QT_MAJOR_VERSION}::UiTools")
                        # replace Qt${QT_MAJOR_VERSION}::libname with Qtlibname.framework
                        string(REGEX REPLACE "Qt${QT_MAJOR_VERSION}::([a-zA-Z]+)"
                                             "\${VISIT_LIBRARY_DIR}/Qt\\1.framework"
                                             newtoken ${token})
                    else()
                        # replace Qt${QT_MAJOR_VERSION}::libname with Qt${QT_MAJOR_VERSION}
                        string(REGEX REPLACE "Qt${QT_MAJOR_VERSION}::([a-zA-Z]+)"
                                             "Qt${QT_MAJOR_VERSION}\\1"
                                             newtoken ${token})
                    endif()
                else()
                    # replace Qt${QT_MAJOR_VERSION}::libname with Qt${QT_MAJOR_VERSION}
                    string(REGEX REPLACE "Qt${QT_MAJOR_VERSION}::([a-zA-Z]+)"
                                         "Qt${QT_MAJOR_VERSION}\\1"
                                         newtoken ${token})
                endif()
            elseif(token MATCHES "VTK::")
                if(APPLE)
                    set(sepchar ".")
                else()
                    set(sepchar "-")
                endif()
                if(token MATCHES "VTK::vtk")
                    string(REPLACE "VTK::" "" atoken ${token})
                else()
                    string(REPLACE "VTK::" "vtk" atoken ${token})
                endif()

                # append VTK version to vtk lib names
                if(atoken MATCHES "WrappingPythonCore")
                    string(REPLACE "PythonCore"
                           "Python${PYTHON_SMALL_VERSION}Core-${VTK_SMALL_VERSION}" newtoken ${atoken})
                elseif(${atoken} MATCHES "vtkWrappingTools")
                  # Skip this static library.
                  set(skip_next_token TRUE)
                  continue()
                else()
                    set(newtoken "${atoken}${sepchar}${VTK_SMALL_VERSION}")
                endif()
            elseif(${token} IN_LIST VTK_TARGETS)
                if(APPLE)
                    set(sepchar ".")
                else()
                    set(sepchar "-")
                endif()
                if(token MATCHES "VTK::")
                    string(REPLACE "VTK::" "vtk" atoken ${token})
                else()
                    set(atoken ${token})
                endif()

                # append VTK version to vtk lib names
                if(atoken MATCHES "WrappingPythonCore")
                    string(REPLACE "PythonCore"
                           "Python${PYTHON_SMALL_VERSION}Core-${VTK_SMALL_VERSION}" newtoken ${atoken})
                elseif(${atoken} MATCHES "vtkWrappingTools")
                  # Skip this static library.
                  set(skip_next_token TRUE)
                  continue()
                else()
                    set(newtoken "${atoken}${sepchar}${VTK_SMALL_VERSION}")
                endif()
            elseif(${token} MATCHES "mpich")
              # If we are installing mpich, then VISIT_PARALLEL_LINKER_FLAGS
              # points to our installed mpich, so having it in depds list
              # seems unnecessary, lets skip it then.
              # want to say skip the next token which should be 'general'
              set(skip_next_token TRUE)
              continue()
            elseif(${token} MATCHES "icet")
              # Static libs, not necessary to be listed as a dependency here
              continue()
            elseif(${token} MATCHES "vtkm_")
              # Static libs, not necessary to be listed as a dependency here
              continue()
            elseif(${token} MATCHES "OSMesa")
                string(REPLACE "mesagl" "osmesa" newtoken ${token})
                string(REPLACE "OSMesa.so.8" "GL.so.1" newtoken ${newtoken})
            else()
                if(WIN32)
                    if(token MATCHES "windowsbuild")
                        # strip off location and extension
                        get_filename_component(libname ${token} NAME_WE)
                        set(newtoken "${libname}")
                    elseif (token MATCHES "Program Files") #MS_MPI?
                        # this is most likely MSMPI, handled through PARALLEL vars
                        set(newtoken "")
                    else()
                        set(newtoken ${token})
                    endif()
                else()
                    if(${token} MATCHES "tbb")
                        get_filename_component(libname ${token} NAME)
                        set(newtoken "${libname}")
                    elseif(${token} MATCHES "embree")
                        get_filename_component(libname ${token} NAME)
                        set(newtoken "${libname}")
                    elseif(${token} MATCHES "ospray")
                        get_filename_component(libname ${token} NAME)
                        set(newtoken "${libname}")
                    else()
                        set(newtoken ${token})
                    endif()
                endif()
            endif()
            list(APPEND filteredline ${newtoken})
        endforeach()
        # Sometimes the last tokens get filtered so the corresponding ';")' is missing
        # causing syntax errors. Need to check if filteredline ends with '")' if not add it
        if(NOT "${filteredline}" MATCHES "\\)")
            list(APPEND filteredline "\")")
        endif()
        file(APPEND ${filename} "${filteredline}\n")
        unset(filteredline)
    endforeach()
endfunction()


FILTER_VISIT_LIB_DEPENDENCIES(${VISIT_BINARY_DIR}/include/VisItLibraryDependencies.cmake)
